<template>
  <div style="height: 100vh; display: flex; flex-direction: column;">
    <!-- 导航栏 - 固定高度 -->
    <div style="height: 80px; background: white; border-bottom: 1px solid #ddd; display: flex; align-items: center; padding: 0 30px; flex-shrink: 0; position: relative; z-index: 1000;">
      <div style="font-size: 24px; font-weight: bold; color: #1890ff;">⚖️ 法律文献检索平台</div>
      <div style="flex: 1; margin: 0 30px; position: relative;">
        <a-auto-complete
          v-model:value="searchValue"
          :options="searchHistoryOptions"
          placeholder="搜索案件、法条..."
          size="large"
          style="width: 100%;"
          @focus="loadSearchHistory"
          @select="onSelectHistory"
        >
          <template #default>
            <a-input-search
              v-model:value="searchValue"
              placeholder="搜索案件、法条..."
              enter-button="搜索"
              size="large"
              @search="onSearch"
            />
          </template>
        </a-auto-complete>
      </div>
      <div style="display: flex; align-items: center; gap: 12px; cursor: pointer;" @click="handleUserCenter">
        <a-avatar v-if="userInfo" :size="36" :src="userInfo.avatar">
          {{ userInfo.username.charAt(0).toUpperCase() }}
        </a-avatar>
        <a-avatar v-else :size="36" style="background-color: #ccc">
          <UserOutlined />
        </a-avatar>
        <span style="font-size: 16px;">
          <span v-if="userInfo">{{ userInfo.username }}</span>
          <span v-else>登录/注册</span>
        </span>
      </div>
    </div>

    <!-- 内容区域 -->
    <div style="flex: 1;">
      <!-- 轮播图 -->
      <div style="height: 300px;">
        <a-carousel autoplay>
          <div><div style="height: 300px; background: linear-gradient(45deg, #1890ff, #722ed1); color: white; display: flex; align-items: center; justify-content: center; font-size: 24px;">智能法律检索平台</div></div>
          <div><div style="height: 300px; background: linear-gradient(45deg, #52c41a, #1890ff); color: white; display: flex; align-items: center; justify-content: center; font-size: 24px;">专业案例分析</div></div>
          <div><div style="height: 300px; background: linear-gradient(45deg, #faad14, #52c41a); color: white; display: flex; align-items: center; justify-content: center; font-size: 24px;">法规实时更新</div></div>
        </a-carousel>
      </div>

      <!-- 热点案件 -->
      <div style="padding: 40px 20px; background: #fafafa;">
        <h2 style="text-align: center; margin-bottom: 30px; color: #1890ff;">🔥 热点案件</h2>
        
        <a-spin :spinning="loading">
          <a-row :gutter="[16, 16]" v-if="cases.length > 0">
            <a-col :span="6" v-for="item in cases" :key="item.id">
              <a-card hoverable style="height: 220px; cursor: pointer;" @click="viewCaseDetail(item)">
                <div style="height: 100%; display: flex; flex-direction: column; justify-content: space-between;">
                  <div>
                    <h3 style="margin-bottom: 8px; font-size: 16px;">{{ item.caseNumber }}</h3>
                    <p style="color: #666; margin-bottom: 8px; font-size: 14px;">{{ item.parties }}</p>
                    <p style="color: #999; font-size: 12px; margin-bottom: 12px;">{{ item.court }}</p>
                  </div>
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
                    <span style="font-size: 12px; color: #999;">{{ item.createTime }}</span>
                  </div>
                </div>
              </a-card>
            </a-col>
          </a-row>
          
          <div v-else-if="!loading" style="text-align: center; padding: 40px; color: #999;">
            暂无热门案件数据
          </div>
        </a-spin>
        
        <!-- <div style="text-align: center; margin-top: 30px;">
          <a-button type="primary" size="large" @click="viewMoreCases">
            查看更多案件
          </a-button>
        </div> -->
      </div>
    </div>
    
    <!-- 登录模态框 -->
    <LoginModal
      v-model:open="showLoginModal"
      @loginSuccess="handleLoginSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined } from '@ant-design/icons-vue'
import { getHotCases } from '@/api/case'
import { getCurrentUserInfo } from '@/api/user'
import { getSearchHistory } from '@/api/search'
import LoginModal from '@/components/LoginModal.vue'

const router = useRouter()
const cases = ref([])
const loading = ref(false)
const showLoginModal = ref(false)
const userInfo = ref(null)
const searchValue = ref('')
const searchHistoryOptions = ref([])

// 加载搜索历史
const loadSearchHistory = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    searchHistoryOptions.value = []
    return
  }
  
  try {
    const response = await getSearchHistory()
    if (response.code === 200 && response.data) {
      searchHistoryOptions.value = response.data.map(item => ({
        value: item.query || item,
        label: item.query || item
      }))
    } else {
      searchHistoryOptions.value = []
    }
  } catch (error) {
    console.error('获取搜索历史出错:', error)
    searchHistoryOptions.value = []
  }
}

// 选择历史记录
const onSelectHistory = (value) => {
  searchValue.value = value
  onSearch(value)
}

// 搜索功能
const onSearch = (value) => {
  const query = value || searchValue.value
  if (query && query.trim()) {
    router.push({ name: 'Search', query: { q: query.trim() } })
  }
}

// 获取热门案件
const loadHotCases = async () => {
  try {
    loading.value = true
    const response = await getHotCases()
    cases.value = response.data || []
  } catch (error) {
    console.error('获取热门案件出错:', error)
    cases.value = []
  } finally {
    loading.value = false
  }
}

// 获取用户信息
const loadUserInfo = async () => {
  const token = localStorage.getItem('token')
  if (token) {
    try {
      const response = await getCurrentUserInfo()
      if (response.code === 200) {
        userInfo.value = response.data
      } else {
        console.error('获取用户信息失败:', response.msg)
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
      }
    } catch (error) {
      console.error('获取用户信息出错:', error)
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
}

// 查看案件详情
const viewCaseDetail = (caseItem) => {
  router.push({ name: 'CaseDetail', params: { id: caseItem.id } })
}

// 查看更多案件
const viewMoreCases = () => {
  router.push({ name: 'Search' })
}

// 获取案件状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '进行中',
    1: '已结案', 
    2: '上诉'
  }
  return statusMap[status] || '未知'
}

// 获取案件状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: 'processing',
    1: 'success',
    2: 'warning'
  }
  return colorMap[status] || 'default'
}

// 处理用户中心点击
const handleUserCenter = () => {
  if (userInfo.value) {
    router.push({ name: 'Profile' })
  } else {
    showLoginModal.value = true
  }
}

// 登录成功后的处理
const handleLoginSuccess = () => {
  loadUserInfo()
}

// 页面加载时初始化
onMounted(() => {
  loadHotCases()
  loadUserInfo()
})
</script>

<style>
/* 最基础的样式 */
</style>